using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Linq;
using Unity.Mathematics;

namespace EarthUtility
{


    public class JsonHelpers
    {
        public static int getUint32OrDefault(JToken json, string key, int defaultV)
        {
            var j = json[key];
            return j == null ? defaultV : j.Value<int>();
        }
        public static List<double> getDoubles(JToken json, string key)
        {
            JToken array = json[key];
            List<double> result = new List<double>();
            foreach (var item in array)
            {
                result.Add(item.Value<double>());
            }
            return result;
        }

        public static string getStringOrDefault(JToken json, string key, string defaultV)
        {
            var j = json[key];
            return j == null ? defaultV : j.Value<string>();
        }
        public static List<string> getStrings(JToken json, string key)
        {
            var j = json[key] as JArray;
            if (j != null)
            {
                return j.Select(x => x.Value<string>()).ToList();
            }
            return new List<string>();
        }

        internal static double4x4? getTransformProperty(JToken tileJson, string key)
        {
            var a = tileJson[key];
            if (a == null || a.Count() < 16)
            {
                return null;
            }

            foreach (JToken v in a)
            {
                if (v.Type != JTokenType.Float)
                {
                    return null;
                }
            }

            return new double4x4(
                new double4(
                    (double)a[0],
                    (double)a[1],
                    (double)a[2],
                    (double)a[3]),
               new double4(
                    (double)a[4],
                    (double)a[5],
                    (double)a[6],
                    (double)a[7]),
               new double4(
                    (double)a[8],
                    (double)a[9],
                    (double)a[10],
                    (double)a[11]),
               new double4(
                    (double)a[12],
                    (double)a[13],
                    (double)a[14],
                    (double)a[15]));
        }

        internal static double? getScalarProperty(JToken tileJson, string key)
        {
            var j = tileJson[key];
            if(j==null) return null;
            return j.Value<double>();
        }
    }
}